package interceptors

import (
	"aquaman/app/infra/db/ctxdb"
	"aquaman/app/infra/job"
	"context"
	"google.golang.org/grpc"
)

func UnaryServerInterceptor(db *ctxdb.CtxDB) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, returnErr error) {
		newCtx := db.NewContextWithTx(ctx)
		defer db.RollbackUnlessCommitted(newCtx)

		return handler(newCtx, req)
	}
}

func JobTaskInterceptor(db *ctxdb.CtxDB) job.TaskInterceptor {
	return func(next job.Task) job.Task {
		return func(ctx context.Context) error {
			newCtx := db.NewContextWithTx(ctx)
			defer db.RollbackUnlessCommitted(newCtx)
			return next(newCtx)
		}
	}
}
